package magnet.processor.registry.instances;

import java.util.*;

public class SectionsCreatorVisitor implements Model.InstVisitor {

    private List<Model.Section> sections;

    private Map<String, Model.Section> sectionsByType = new LinkedHashMap<>();
    private Model.Range currentRange = null;

    @Override
    public void visit(Model.Inst inst) {
        if (currentRange == null) {
            addRange(inst);
            return;
        }

        if (currentRange != null) {
            if (currentRange.getType().equals(inst.getType())
                    && currentRange.getClassifier().equals(inst.getClassifier())) {
                currentRange.getImpls().add(inst);
                return;
            }
            addRange(inst);
            return;
        }
    }

    public List<Model.Section> getSections() {
        sections = new ArrayList<>();
        Iterator<Model.Section> iterator = sectionsByType.values().iterator();
        while (iterator.hasNext()) {
            sections.add(iterator.next());
        }
        return sections;
    }

    private void addRange(Model.Inst inst) {

        Model.Section section = sectionsByType.get(inst.getType());
        if (section == null) {
            section = new Model.Section(inst.getType());
            sectionsByType.put(inst.getType(), section);
        }

        int rangeIndex = calculateIndex();
        Model.Range range = new Model.Range(inst.getType(), inst.getClassifier(), inst, rangeIndex);
        section.ranges.put(range.getClassifier(), range);

        currentRange = range;
    }

    private int calculateIndex() {

        if (currentRange != null) {
            return currentRange.getFrom() + currentRange.getImpls().size();
        }
        return 0;
    }
}
